package com.phonemap.models;

import java.util.ArrayList;
import java.util.List;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.phonemap.common.Util;

public class ViewType {

	public static Entity createOrUpdateViewType(String name) {
		Entity viewType = getSingleViewType(name);
		if (viewType == null) {
			viewType = new Entity("ViewType", name);
			viewType.setProperty("name", name);
		} else {
			viewType.setProperty("name", name);
		}
		Util.persistEntity(viewType);
		return viewType;
	}

	public static Entity getSingleViewType(String name) {
		Iterable<Entity> results = Util.listEntities("ViewType", "name", name);
		List<Entity> entity = new ArrayList<Entity>();
		for (Entity e : results)
			if (e != null)
				entity.add(e);
		if (!entity.isEmpty()) {
			return (Entity) entity.remove(0);
		}
		return null;
	}

	public static Iterable<Entity> getAllViewTypes() {
		Iterable<Entity> entities = Util.listEntities("ViewType", null, null);
		return entities;
	}

	public static Iterable<Entity> getAllViewTypes(String kind) {
		Iterable<Entity> entities = Util.listEntities(kind, null, null);
		return entities;
	}

	public static Entity getViewType(String name) {
		Key key = KeyFactory.createKey("ViewType", name);
		return Util.findEntity(key);
	}

	public static Iterable<Entity> getViewTypes(String name) {
		Iterable<Entity> entities = Util.listEntities("ViewType", "name",
				name);
		return entities;
	}

	/**
	 * Delete product entity
	 * 
	 * @param productKey
	 *            : product to be deleted
	 * @return status string
	 */
	public static String deleteViewType(String name) {
		Key key = KeyFactory.createKey("ViewType", name);

//		List<Entity> items = getPositions(productKey);
//		if (!items.isEmpty()) {
//			return "Cannot delete, as there are items associated with this product.";
//		}
		Util.deleteEntity(key);
		return "ViewType deleted successfully";
	}

	public static Iterable<Entity> getViewTypes(String searchBy,
			String searchFor) {
		return Util.listEntities("ViewType", searchBy, searchFor);
	}
}
